import sys

data = sys.stdin.readlines()
#data =["1", "babaab"]

lookup = {}
lookup["ab"] = "c"
lookup["bc"] = "a"
lookup["ca"] = "b"
lookup["ba"] = "c"
lookup["cb"] = "a"
lookup["ac"] = "b"

def read_data(strs):
    ncount = data[0]
    ncount = int(ncount)
    count = 0;
    for strin in data[1:]:
        strs.append(strin.strip())
        count = count + 1
        if(count == ncount): break
    return ncount

def max_reduce_left_to_right(input_str):
    size = len(input_str)
    if(size <= 1): return size
    if(size == 2):
        if(input_str[0] == input_str[1]):
            return 2
        else:
            return 1 
    is_more = True
    while is_more:
        is_more = False
        new_list = ""
        i = 0
        size = len(input_str)
        while i + 1 < size:
            if(input_str[i] != input_str[i + 1]):
                new_list = new_list + lookup[input_str[i: i+2]]
                is_more = True
                i = i + 2
            else:
                new_list = new_list + input_str[i]
                i = i + 1
        if(i < size):
            new_list = new_list + input_str[i]
        input_str = new_list
    return len(input_str)

def max_reduce_iter(input_str):
    reverse_str = input_str[::-1]
    x1, x2 = max_reduce_left_to_right(input_str), max_reduce_left_to_right(reverse_str)
    #if(x1 != x2): print(input_str)
    return min(x1, x2)

def max_reduce_shuffled(input_str):
    min_len = len(input_str)
    for i in range(1, min_len):
        new_str = input_str[i:] + input_str[:i]
        candi = max_reduce_iter(new_str)
        if(min_len > candi): min_len = candi
    return min_len

strs = []
read_data(strs)

for cstr in strs:
    print(max_reduce_shuffled(cstr))
   
   
   
#testing code:
import time
import random
random.seed(time.time())

dic = ["a", "b", "c"]
def gen_rand():
    ret = ""
    for i in range(6):
        ret = ret + dic[random.randint(0,10) % 3]
    return ret

def test():
    for i in range(100000):
        cstr = gen_rand()
        if(max_reduce_iter(cstr) != max_reduce_shuffled(cstr)):
            print(cstr)

#test()
